package top.jianx.demo.shiro.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import top.jianx.demo.shiro.pojo.User;
import top.jianx.demo.shiro.service.UserService;

/**
 * @Description 自定义realm
 * @ClassName UserRealm
 * @Author Jianx  <[email]jianx@jianx.top>
 * @date 2020.03.03
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService UserService;

    //执行授权
    @Override
    /**
     * 授权
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权");
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //给资源授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        
        //解析权限
        String reg = "[(|)(,)]";
        if (user.getPerms().contains("|") || user.getPerms().contains(",")) {
            String[] splitStr = user.getPerms().split("[(|)(,)]");
            for (int i=0; i < splitStr.length; i++){
                simpleAuthorizationInfo.addStringPermission(splitStr[i]);
            }
        } else {
            simpleAuthorizationInfo.addStringPermission(user.getPerms());
        }
        
        return simpleAuthorizationInfo;
    }

    //执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //shiro判断逻辑
        UsernamePasswordToken user = (UsernamePasswordToken) authenticationToken;
        User realUser = new User();
        realUser.setName(user.getUsername());
        realUser.setPassword(String.copyValueOf(user.getPassword()));
        User newUser = UserService.findUser(realUser);
        //System.out.println(user.getUsername());

        if(newUser == null){
            //用户名错误
            //shiro会抛出UnknownAccountException异常
            return null;
        }

        return new SimpleAuthenticationInfo(newUser,newUser.getPassword(),"");
    }
}
